package com.fa4j.common.base.util;

import com.fa4j.common.base.exception.CommonRequestError;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import org.apache.commons.lang3.ObjectUtils;

import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 校验工具类型
 */
public class ValidUtil {


    /**
     * 校验值不能为空
     *
     * @param name  检查名称
     * @param value 校验的值
     */
    public static void validNotEmpty(String name, Object value) {
        if (ObjectUtils.isEmpty(value)) {
            throw CommonRequestError.NOT_EMPTY.build(name);
        }
    }


    public static void valid(Validator validator, Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> violations = validator.validate(object, groups);
        if (!violations.isEmpty()) {
            throw new ConstraintViolationException(violations);
        }
    }

    /**
     * 校验值不能全为为空
     *
     * @param name   检查名称
     * @param values 校验的值
     */
    public static void validNotAllEmpty(String name, Object... values) {
        if (Arrays.stream(values).allMatch(ObjectUtils::isEmpty)) {
            throw CommonRequestError.NOT_EMPTY.build(name);
        }
    }

    /**
     * 校验值是否被占用
     *
     * @param name     检查名称
     * @param value    校验的值
     * @param findFund 查询方法
     */
    public static void validInUsed(String name, String value, Function<String, Optional<?>> findFund) {
        if (value == null || value.isEmpty()) {
            return;
        }
        if (findFund.apply(value).isPresent()) {
            throw CommonRequestError.IN_USED.build(name);
        }
    }

    /**
     * 校验值是否被占用
     *
     * @param name     检查名称
     * @param findFund 查询方法
     */
    public static void validInUsed(String name, Supplier<Optional<?>> findFund) {
        if (findFund.get().isPresent()) {
            throw CommonRequestError.IN_USED.build(name);
        }
    }
}
